﻿# -*- coding: utf-8 -*-
import json, datetime
from django.http import HttpResponse
from django.shortcuts import render_to_response

from basecfg.models import Person
from bank import settings



from django.forms.models import model_to_dict
from django.db.models import Q

#数据模型转换成json    model = models.Model  ext:不需要的字段  q:查询条件
def ModelToJson(model, ext=[], page=1, rows=10, q=Q()):
    try:
        page = int(page)
        rows = int(rows)
    except ValueError:
        page = 1
        rows = 10
    offset = (page - 1) * rows
    obj = model.objects.filter(q)
    total = obj.count()
    if offset is not 0:
        rows = rows + offset
    elif total <= rows:
        rows = total
    obj = obj.all()[offset:rows]
    ls = []
    for o in obj:
        o = model_to_dict(o)
        d = {}
        for f in model._meta.fields:
            if f.name  not in ext:
                if type(o[f.name]) == type(datetime.date.today()):
                    d[f.name] = str(o[f.name])
                else:
                    d[f.name] = o[f.name]
        ls.append(d)
    li = {"rows": ls, "total": total}
    rtn = json.dumps(li)
    return rtn


def tbl_json_persen(request):
    jsonTbl = ModelToJson(Person, [], request.GET['page'], request.GET['rows'])
    response = HttpResponse()
    response.write(jsonTbl)
    return response

